package com.example.test.channel;

import org.junit.Test;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.charset.Charset;

/**
 * @Author: fxy
 * @Date: 2022/01/07/9:07
 * @Description:
 */
public class Demo3 {
    public static void main(String[] args) {

    }
    @Test
    public void sendDatagram() throws Exception {
        DatagramChannel sendChannel = DatagramChannel.open();
        InetSocketAddress sendAddress = new InetSocketAddress("127.0.1",9999);

        while(true){
            ByteBuffer buffer = ByteBuffer.wrap("发送efrgt".getBytes());
            sendChannel.send(buffer,sendAddress);
            System.out.println("发送完成");
            Thread.sleep(1000);
        }
    }

    @Test
    public void receiveDatagram() throws Exception {
        DatagramChannel receiveChannel = DatagramChannel.open();
        InetSocketAddress receiveAddress = new InetSocketAddress(9999);
        receiveChannel.bind(receiveAddress);

        ByteBuffer receiveBuffer = ByteBuffer.allocate(1024);
        while(true){
            receiveBuffer.clear();
            SocketAddress socketAddress = receiveChannel.receive(receiveBuffer);
            receiveBuffer.flip();
            System.out.println(socketAddress.toString());
            System.out.println(Charset.forName("utf-8").decode(receiveBuffer));
        }
    }

    @Test
    public void testConnect() throws Exception {
        DatagramChannel connChannel = DatagramChannel.open();
        connChannel.bind(new InetSocketAddress(9999));
        connChannel.connect(new InetSocketAddress("127.0.0.1",9999));
        connChannel.write(ByteBuffer.wrap("发送efrgthhhhhhhhhhhhh".getBytes()));
        ByteBuffer readBuffer = ByteBuffer.allocate(100);
        while (true){
            readBuffer.clear();
            connChannel.read(readBuffer);
            readBuffer.flip();
            System.out.println(Charset.forName("utf-8").decode(readBuffer));

        }
    }
}
